package afk.lib;

import java.io.*;
import java.util.*;

public class FileFunctions
{

	public static void delEmptyDirs(final File root)
	{
		if (root == null)
			return;
		if (root.isFile())
			return;
		final File[] children = root.listFiles();
		for (final File file : children)
			delEmptyDirs(file);
		root.delete();
	}

	public static String bomToEncoding(final byte[] bom)
	{
		if (bom.length < 2)
			return null;
		if (isEqual(bom, 0xfe, 0xff))
			return "UTF-16BE";
		if (isEqual(bom, 0xff, 0xfe))
			return "UTF-16LE";

		if (bom.length < 3)
			return null;
		if (isEqual(bom, 0xef, 0xbb, 0xbf))
			return "UTF-8";
		if (isEqual(bom, 0xf7, 0x64, 0x4c))
			return "UTF-1";
		if (isEqual(bom, 0x0e, 0xfe, 0xff))
			return "SCSU";
		if (isEqual(bom, 0xfb, 0xee, 0x28))
			return "BOCU-1";

		if (bom.length < 4)
			return null;
		if (isEqual(bom, 0x00, 0x00, 0xfe, 0xff))
			return "UTF-32BE";
		if (isEqual(bom, 0xfe, 0xff, 0x00, 0x00))
			return "UTF-32LE";
		if (isEqual(bom, 0x2b, 0x2f, 0x76, 0x38))
			return "UFT-7";
		if (isEqual(bom, 0x2b, 0x2f, 0x76, 0x39))
			return "UFT-7";
		if (isEqual(bom, 0x2b, 0x2f, 0x76, 0x2b))
			return "UFT-7";
		if (isEqual(bom, 0x2b, 0x2f, 0x76, 0x2f))
			return "UFT-7";
		if (isEqual(bom, 0x84, 0x31, 0x95, 0x33))
			return "GB18030";
		if (isEqual(bom, 0xdd, 0x73, 0x66, 0x73))
			return "UTF-EBCDIC";
		return null;
	}

	private static boolean isEqual(final byte[] bom, final int... values)
	{
		for (int i = 0; i < values.length; i++)
			if ((bom[i] & 0xff) != values[i])
				return false;
		return true;
	}

	public static byte[] read(final File file, final int offset, final int size)
	{
		try
		{
			final RandomAccessFile raf = new RandomAccessFile(file, "r");
			try
			{
				final byte[] result = new byte[size];
				final int read = raf.read(result);
				if (read == size)
					return result;
				if (read == -1)
					return new byte[0];
				return Arrays.copyOf(result, read);
			}
			finally
			{
				raf.close();
			}
		}
		catch (final FileNotFoundException e)
		{
			return null;
		}
		catch (final IOException e)
		{
			return null;
		}
	}
}
